<template>
 <x-button slot="right" mini class="btn" :disabled="disabled || time > 0">{{text}}</x-button>
</template>

<script>
import { XButton } from 'vux'
import { mapMutations } from 'vuex'
export default {
  name: 'Countdown',
  components: {
    XButton
  },
  props: {
    second: {
      type: Number,
      default: 60
    },
    disabled: {
      type: Boolean,
      default: false
    },
    cellphone: {}
  },
  data () {
    return {
      time: 0
    }
  },
  methods: {
    /**
     * [run 组件初始化使time等于父组件传进来的数值然后调用count函数]
     * @return {[type]} [description]
     */
    run () {
      this.time = this.second
      this.$store.dispatch('message', this.cellphone).then((res) => {
        let result = res.data
        if (result === 101) {
          this.setToast({
            show: true,
            type: '',
            text: result.Message
          })
        } else {
          this.setToast({
            show: true,
            type: 'text',
            text: result.Message
          })
        }
      })
      this.count()
    },
    /**
     * [count 每秒钟使time减1]
     * @return {[type]} [description]
     */
    count () {
      if (this.time > 0) {
        this.time--
        setTimeout(this.count, 1000)
      }
    },
    ...mapMutations({
      setToast: 'setShowToast'
    })
  },
  computed: {
    /**
     * [text 观察time的变化]
     * @return {[type]} [判断time的值然后返回字符串]
     */
    text () {
      return this.time > 0 ? this.time + 's 后重新获取' : '获取验证码'
    }
  }
}
</script>

<style>
.weui-vcode .weui-btn_mini{
  font-size:16px;
  width: 6.5rem;
  padding: 0;
  height: 40px;
}
</style>
